<template>
  <van-form @submit="onSubmit">
    <van-field
      v-model="username"
      name="用户名"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="password"
      type="password"
      name="密码"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <div style="margin: 16px">
      <van-button round block type="info" native-type="submit">登录</van-button>
    </div>
  </van-form>
</template>

<script>
import { mapActions } from "vuex";
import { loginApi } from "../http/userApi";
export default {
  name: "LoginForm",
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    ...mapActions(["userStore/loginAction"]),
    onSubmit() {
      loginApi(this.username, this.password)
        .then((res) => {
          console.log("登录成功：", res.data);
          this["userStore/loginAction"](res.data.data);

          this.username = "";
          this.password = "";
          let url = this.$route.query.redirect
            ? this.$route.query.redirect
            : "/";
          this.$router.push(url);
        })
        .catch((err) => {
          console.log("登陆失败：", err);
        });
    },
  },
};
</script>